<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>大文件分片</title>
</head>
<body>
<input type="file">

<script src="./utils/spark-md5.js"></script>
<script>

    const inpFile = document.querySelector('input[type="file"]')
    // 分片大小
    const CHUNK_SIZE = 5 * 1024 * 1024
    // 获取当前设备的线程数量
    const THREAD_COUNT = navigator.hardwareConcurrency || 4;

    inpFile.onchange = async (e) => {
        const file = e.target.files[0]
        // 分片
        const chunks = await cutFile(file)
        console.log(chunks)
    }

    async function cutFile(file) {
        return new Promise((resolve)=>{
            const chunkCount = Math.ceil(file.size / CHUNK_SIZE)
            const result = []
            let finishCount = 0 // 完成的线程数量
            // 计算每个线程处理的分片数量
            const threadChunkCount = Math.ceil(chunkCount / THREAD_COUNT)
            for (let i = 0; i < THREAD_COUNT; i++) {
                // 给每个线程分配任务
                const worker = new Worker('./utils/worker.js', {
                    type: 'module',
                })
                let start = i * threadChunkCount
                let end = Math.min((i + 1) * threadChunkCount, chunkCount)
                worker.postMessage({
                    file,
                    start, // 起始分片下标
                    end,  // 结束分片下标
                    chunkSize: CHUNK_SIZE
                })
                worker.onmessage = (e) => {
                    worker.terminate() // 终止线程
                    result[i] = e.data
                    finishCount++
                    if(finishCount === THREAD_COUNT){
                        resolve(result.flat())
                    }
                }
            }
        })
    }


</script>
</body>
</html>